import { DataTypes, Model, type Optional } from 'sequelize'
import  sequelize  from '../config'

// 题目领域枚举
export enum TopicDomain {
  HTML = 'html',
  JS = 'js',
  CSS = 'css',
  VUE = 'vue',
  ENGINEERING = '工程化'
}

// 难度枚举
export enum Difficulty {
  BASIC = '基础',
  MEDIUM = '中等',
  HARD = '困难'
}

// 审核状态枚举
export enum ReviewStatus {
  PENDING = 'pending',    // 待审核
  APPROVED = 'approved',  // 已通过
  REJECTED = 'rejected'   // 已拒绝
}

// 题目属性接口
export interface TopicAttributes {
  id: number
  title: string
  domain: TopicDomain
  difficulty: Difficulty
  reviewStatus: ReviewStatus
  reviewReason?: string
  submitterId: number
  starCount: number
  standardAnswer: string
  description?: string
  createdAt?: Date
  updatedAt?: Date
}

// 创建题目时的可选属性
export type TopicCreationAttributes = Optional<TopicAttributes, 'id' | 'reviewReason' | 'description' | 'starCount' | 'createdAt' | 'updatedAt'>

// 题目模型类
export class Topic extends Model<TopicAttributes, TopicCreationAttributes> implements TopicAttributes {
  public id!: number
  public title!: string
  public domain!: TopicDomain
  public difficulty!: Difficulty
  public reviewStatus!: ReviewStatus
  public reviewReason?: string
  public submitterId!: number
  public starCount!: number
  public standardAnswer!: string
  public description?: string
  public readonly createdAt!: Date
  public readonly updatedAt!: Date
}

// 定义题目模型
Topic.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    title: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '题目标题'
    },
    domain: {
      type: DataTypes.ENUM(...Object.values(TopicDomain)),
      allowNull: false,
      comment: '题目领域'
    },
    difficulty: {
      type: DataTypes.ENUM(...Object.values(Difficulty)),
      allowNull: false,
      comment: '题目难度'
    },
    reviewStatus: {
      type: DataTypes.ENUM(...Object.values(ReviewStatus)),
      allowNull: false,
      defaultValue: ReviewStatus.PENDING,
      comment: '审核状态'
    },
    reviewReason: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '审核原因'
    },
    submitterId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '提交人用户ID'
    },
    starCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '收藏数量'
    },
    standardAnswer: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: '标准答案'
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '题目描述'
    }
  },
  {
    sequelize,
    tableName: 'topics',
    timestamps: true,
    indexes: [
      {
        fields: ['domain']
      },
      {
        fields: ['difficulty']
      },
      {
        fields: ['reviewStatus']
      },
      {
        fields: ['submitterId']
      },
      {
        fields: ['starCount']
      }
    ]
  }
)

export default Topic
